// src/mock/index.js
import Mock from 'mockjs'
import userService from './services/user'
import bookService from './services/book'

// 设置延迟时间
Mock.setup({
  timeout: '200-600'
})

// 注册所有服务
const services = {
  ...userService,
  ...bookService
}

// 注册所有 mock 接口
Object.keys(services).forEach(key => {
  const [method, path] = key.split(' ')
  const handler = services[key]

  // 将路由参数转换为正则表达式
  const regexPath = path
    // .replace(/\//g, '\\/') // 首先转义斜杠
    .replace(/:\w+/g, '(\\w+)') // 然后转换参数为捕获组
    + '(\\?.*)?$' // 添加结束标记确保完整匹配

  Mock.mock(new RegExp(regexPath), method.toLowerCase(), (options) => {
    console.log(options.url)
    // 处理 URL 参数
    if (path.includes(':')) {
      const paramNames = path.match(/:\w+/g).map(p => p.slice(1))
      const matches = options.url.match(new RegExp(regexPath))
      
      if (matches) {
        options.params = {}
        // 从捕获组中提取参数值（跳过第一个完整匹配）
        paramNames.forEach((name, index) => {
          options.params[name] = matches[index + 1]
        })
      }
    }

    // 处理响应
    if (typeof handler === 'function') {
      return handler(options)
    }
    return handler
  })
})

export default Mock